<template>
  <div class="track-container">
    <!-- 搜索和筛选区域 -->
    <el-card class="search-card" shadow="never">
      <div class="search-section">
        <div class="search-inputs">
          <el-input
            v-model="searchKeyword"
            placeholder="输入订单号搜索"
            clearable
            style="width: 300px;"
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          
          <el-select
            v-model="statusFilter"
            placeholder="筛选状态"
            clearable
            style="width: 200px;"
            @change="handleStatusFilter"
          >
            <el-option label="全部状态" value="" />
            <el-option
              v-for="(status, key) in statusMap"
              :key="key"
              :label="status.text"
              :value="key"
            />
          </el-select>

          <OrderSelector 
            v-if="orderOptions.length > 0"
            :key="`order-selector-${userRole}-${orderOptions.length}`"
            v-model:selected-order="selectedOrder"
            :order-options="filteredOrderOptions"
            @update:selected-order="handleOrderChange"
          />
        </div>
        
        <div class="search-stats" v-if="orderOptions.length > 0">
          <el-tag type="info" size="small">
            总计 {{ orderOptions.length }} 个订单
          </el-tag>
          <el-tag v-if="filteredOrderOptions.length !== orderOptions.length" type="warning" size="small">
            筛选后 {{ filteredOrderOptions.length }} 个
          </el-tag>
        </div>
      </div>
    </el-card>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 地图区域 -->
      <el-card class="map-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <div class="header-info">
              <h3>配送路线图</h3>
              <div class="order-info" v-if="selectedOrderInfo">
                <el-tag type="primary" size="small">
                  {{ selectedOrderInfo.orderNumber }}
                </el-tag>
                <span class="route-info">
                  {{ selectedOrderInfo.senderAddress ? getCityFromAddress(selectedOrderInfo.senderAddress) : selectedOrderInfo.senderName || '未知' }} → 
                  {{ getCityFromAddress(selectedOrderInfo.receiverAddress) }}
                </span>
              </div>
            </div>
            <div class="map-controls">
              <el-button-group size="small">
                <el-button :icon="ZoomIn" @click="zoomIn">放大</el-button>
                <el-button :icon="ZoomOut" @click="zoomOut">缩小</el-button>
                <el-button :icon="Refresh" @click="resetMap">重置</el-button>
              </el-button-group>
            </div>
          </div>
        </template>
        
        <div class="map-container">
          <MapContainer 
            :selected-order="selectedOrder"
            :track-activities="trackActivities"
            :loading="trackLoading"
            :order-info="selectedOrderInfo ? {
              senderAddress: selectedOrderInfo.senderAddress || `${selectedOrderInfo.senderName}的位置`,
              receiverAddress: selectedOrderInfo.receiverAddress
            } : undefined"
            ref="mapContainerRef"
          />
        </div>
        
        <!-- 地图图例 -->
        <div class="map-legend" v-if="selectedOrder">
          <div class="legend-title">📍 配送路线图例</div>
          <div class="legend-items">
            <div class="legend-item">
              <div class="legend-line expected"></div>
              <span>预期路线：起点到终点的直线距离</span>
            </div>
            <div class="legend-item">
              <div class="legend-line actual"></div>
              <span>实际路线：基于真实轨迹点的配送路径</span>
            </div>
            <div class="legend-item">
              <div class="legend-marker start"></div>
              <span>起始地址（发件人）</span>
            </div>
            <div class="legend-item">
              <div class="legend-marker end"></div>
              <span>目标地址（收件人）</span>
            </div>
            <div class="legend-item">
              <div class="legend-marker current">🚛</div>
              <span>最新位置（实时更新）</span>
            </div>
          </div>
          <div class="legend-note">
            <small>💡 蓝色虚线显示理论最短路径，橙色实线显示实际配送轨迹</small>
          </div>
        </div>
      </el-card>

      <!-- 轨迹详情区域 -->
      <el-card class="track-info-card" shadow="hover">
        <template #header>
          <div class="card-header">
            <div>
              <h3>配送轨迹</h3>
              <div class="track-stats">
                <el-tag v-if="selectedOrder" type="info" size="small">
                  订单ID: {{ selectedOrder }}
                </el-tag>
                <el-tag v-if="trackActivities.length > 0" type="success" size="small">
                  {{ trackActivities.length }} 条轨迹记录
                </el-tag>
                <el-tag v-if="currentStatus" :type="currentStatus.type" size="small">
                  {{ currentStatus.text }}
                </el-tag>
              </div>
            </div>

          </div>
        </template>
        
        <div class="track-content">
          <div v-if="!selectedOrder" class="empty-state">
            <el-empty description="请选择订单查看轨迹信息">
              <el-button type="primary" @click="selectFirstOrder">选择第一个订单</el-button>
            </el-empty>
          </div>
          
          <div v-else-if="trackLoading" class="loading-state">
            <el-skeleton :rows="5" animated />
          </div>
          
          <div v-else-if="trackActivities.length === 0" class="empty-state">
            <el-empty description="该订单暂无轨迹记录">
              <el-button @click="refreshTrackData">重新加载</el-button>
            </el-empty>
          </div>
          
          <TrackTimeline 
            v-else
            :key="selectedOrder"
            :selected-order="selectedOrder"
            :loading="trackLoading"
            :track-activities="trackActivities"
            @select-order="selectFirstOrder"
            @refresh="refreshTrackData"
            @show-on-map="handleShowOnMap"
          />
        </div>
      </el-card>
    </div>


  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch, nextTick } from 'vue'
import { userApi, type DeliveryOrder, type DeliveryTrack, type TrackRecord } from '@/api/user'
import { courierApi, type DeliveryAssignment } from '@/api/courier'
import { adminApi } from '@/api/settings'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, ZoomIn, ZoomOut } from '@element-plus/icons-vue'
import MapContainer from './components/MapContainer.vue'
import TrackTimeline from './components/TrackTimeline.vue'
import OrderSelector from './components/OrderSelector.vue'

// 响应式数据
const selectedOrder = ref('')
const orderList = ref<DeliveryOrder[]>([])
const trackLoading = ref(false)
const refreshing = ref(false)
const searchKeyword = ref('')
const statusFilter = ref('')

// 地图容器引用
const mapContainerRef = ref()

// 用户角色
const userRole = ref<string>('')

// 订单选项
const orderOptions = ref<Array<{value: string, label: string, order: DeliveryOrder}>>([])

// 轨迹活动数据
const trackActivities = ref<Array<{
  content: string
  timestamp: string
  type: string
  color: string
  location: string
  operator?: string
  remark?: string
  status: number
  coordinates?: [number, number]
}>>([])

// 物流状态映射（与数据库保持一致）
const statusMap = {
  '0': { text: '待揽件', type: 'info', color: '#909399' },
  '1': { text: '待发货', type: 'warning', color: '#E6A23C' },
  '2': { text: '运输中', type: 'primary', color: '#409EFF' },
  '3': { text: '已送达', type: 'warning', color: '#E6A23C' },
  '4': { text: '已签收', type: 'success', color: '#67C23A' },
}

// 计算属性
const filteredOrderOptions = computed(() => {
  let filtered = orderOptions.value

  // 关键词搜索
  if (searchKeyword.value.trim()) {
    const keyword = searchKeyword.value.trim().toLowerCase()
    filtered = filtered.filter(option => 
      option.label.toLowerCase().includes(keyword) ||
      (option.order && option.order.orderNumber && option.order.orderNumber.toLowerCase().includes(keyword))
    )
  }

  // 状态筛选
  if (statusFilter.value) {
    filtered = filtered.filter(option => {
      if (!option.order) return false
      
      // 配送员数据使用status字段，普通用户数据使用orderStatus字段
      const statusValue = (option.order as any).status !== undefined ? (option.order as any).status : (option.order as any).orderStatus
      
      // 确保状态值不是null或undefined，0是有效状态
      return statusValue !== null && statusValue !== undefined && statusValue.toString() === statusFilter.value
    })
  }

  return filtered
})

const selectedOrderInfo = computed(() => {
  if (!selectedOrder.value) return null
  const option = orderOptions.value.find(opt => opt.value === selectedOrder.value)
  return option?.order || null
})

const currentStatus = computed(() => {
  if (!selectedOrderInfo.value) return null
  // 配送员数据使用status字段，普通用户数据使用orderStatus字段
  const statusValue = (selectedOrderInfo.value as any).status || (selectedOrderInfo.value as any).orderStatus
  return statusMap[statusValue?.toString() as keyof typeof statusMap] || null
})

// 方法
const getCityFromAddress = (address: string): string => {
  if (!address) return ''
  const match = address.match(/^(.{2})/)
  return match ? match[1] : address.substring(0, 2)
}

// 获取用户角色
const getUserRole = (): string => {
  // 统一使用 user_role 作为角色存储键名
  const roles = localStorage.getItem('user_role') || ''
  
  console.log('用户角色:', roles)
  
  // 如果仍然为空，尝试从其他地方获取
  if (!roles) {
    // 检查是否能从接口成功获取数据来推断角色
    // 如果能获取到配送记录，说明是配送员
    const checkCourierRole = async () => {
      try {
        const response = await courierApi.getMyAssignments(1, 1)
        if (response.code === 200 && response.data && response.data.list) {
          console.log('检测到配送员角色（通过接口验证）')
          localStorage.setItem('user_role', 'courier')
          return 'courier'
        }
      } catch (error) {
        console.log('非配送员角色')
      }
      return ''
    }
    
    // 异步检查，但先返回空字符串
    checkCourierRole().then(role => {
      if (role) {
        userRole.value = role
        // 重新获取订单列表
        fetchOrderList()
      }
    })
  }
  
  return roles
}



const fetchOrderList = async () => {
  try {
    // 获取用户角色
    userRole.value = getUserRole()
    let response: any
    
    // 如果角色为空，先尝试检测是否为配送员
    if (!userRole.value) {
      console.log('角色未设置，尝试检测配送员身份')
      try {
        const testResponse = await courierApi.getMyAssignments(1, 1)
                 if (testResponse.code === 200 && testResponse.data) {
           console.log('检测到配送员身份，设置角色')
           userRole.value = 'courier'
           localStorage.setItem('user_role', 'courier')
         }
       } catch (error) {
         console.log('非配送员身份，设置为普通用户')
         userRole.value = 'user'
         localStorage.setItem('user_role', 'user')
      }
    }
    
    // 根据不同角色调用不同的API
    if (userRole.value === 'admin') {
      // 管理员：获取所有订单
      console.log('管理员身份，获取所有订单')
      response = await adminApi.getAllOrders({ pageNum: 1, pageSize: 100 })
    } else if (userRole.value === 'courier') {
      // 配送员：获取自己的配送订单
      console.log('配送员身份，获取自己的配送订单')
      const assignmentResponse = await courierApi.getMyAssignments(1, 100)
      
      if (assignmentResponse.code === 200 && assignmentResponse.data) {
        const assignments = assignmentResponse.data.list || []
        console.log('配送员接单数据:', assignments)
        
        // 直接使用配送记录数据，不需要获取完整订单详情
        orderList.value = assignments as any[]
        
        // 构建订单选项
        orderOptions.value = assignments.map((assignment: any) => {
          // 配送员数据使用senderName作为发件人信息
          const senderInfo = assignment.senderName || '未知发件人'
          const receiverCity = getCityFromAddress(assignment.receiverAddress)
          
          // 调试：打印订单状态信息
          console.log('配送员订单数据:', {
            orderNumber: assignment.orderNumber,
            status: assignment.status,
            orderId: assignment.orderId
          })
          
          return {
            value: assignment.orderId.toString(),
            label: `${assignment.orderNumber} - ${senderInfo}到${receiverCity}`,
            order: assignment
          }
        })
        
        console.log('配送员订单列表加载成功:', orderList.value.length)
        return
      }
    } else {
      // 普通用户：获取自己的订单
      console.log('普通用户身份，获取自己的订单')
      response = await userApi.getDeliveryOrderList(1, 100)
    }
    
    // 处理响应数据
    if (response && response.code === 200 && response.data) {
      orderList.value = response.data.list || []
      
      // 构建订单选项
      orderOptions.value = orderList.value.map(order => {
        const senderCity = getCityFromAddress(order.senderAddress)
        const receiverCity = getCityFromAddress(order.receiverAddress)
        // 普通用户订单使用deliveryOrderId
        const orderIdValue = (order as any).deliveryOrderId
        return {
          value: orderIdValue?.toString() || '',
          label: `${order.orderNumber} - ${senderCity}到${receiverCity}`,
          order: order
        }
      })
      
      console.log(`${userRole.value}订单列表加载成功:`, orderList.value.length)
    } else {
      console.error('获取订单列表失败:', response?.message)
      ElMessage.error('获取订单列表失败')
    }
  } catch (error) {
    console.error('获取订单列表异常:', error)
    ElMessage.error('获取订单列表失败')
  }
}

const fetchTrackData = async (orderId: string) => {
  if (!orderId) {
    trackActivities.value = []
    return
  }

  try {
    trackLoading.value = true
    console.log('开始获取轨迹数据，订单ID:', orderId)
    
    const response = await userApi.getTrackByOrderId(Number(orderId))
    console.log('轨迹数据响应:', response)
    
    if (response.code === 200 && response.data) {
      const trackData: DeliveryTrack = response.data
      
      if (trackData.trackRecords && Array.isArray(trackData.trackRecords)) {
        const activities = trackData.trackRecords.map((record: TrackRecord) => {
          const statusInfo = statusMap[record.status?.toString() as keyof typeof statusMap] || 
                        { text: '未知状态', type: 'info', color: '#909399' }
          
          // 处理location字段
          let displayLocation = '未知位置'
          let coordinates: [number, number] | undefined = undefined
          
          if (record.location) {
            if (typeof record.location === 'object') {
              displayLocation = record.location.address || '未知位置'
              if (record.location.longitude && record.location.latitude) {
                coordinates = [record.location.longitude, record.location.latitude]
              }
            } else if (typeof record.location === 'string') {
              try {
                const locationData = JSON.parse(record.location)
                displayLocation = locationData.address || record.location
                if (locationData.longitude && locationData.latitude) {
                  coordinates = [locationData.longitude, locationData.latitude]
                }
              } catch (e) {
                displayLocation = record.location
              }
            }
          }
          
          return {
            content: record.description,
            timestamp: record.timestamp,
            type: statusInfo.type,
            color: statusInfo.color,
            location: displayLocation,
            operator: record.operator,
            remark: record.remark,
            status: record.status,
            coordinates: coordinates
          }
        })
        
        // 按时间排序（最新的在前）
        activities.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime())
        
        // 使用nextTick确保DOM更新的安全性
        await nextTick()
        
        // 添加防护：确保activities是有效数组
        if (Array.isArray(activities)) {
          trackActivities.value = [...activities] // 创建新数组避免引用问题
        } else {
          trackActivities.value = []
        }
        
        console.log('轨迹数据处理完成:', trackActivities.value.length, '条记录')
        
        if (trackActivities.value.length > 0) {
          ElMessage.success(`成功加载 ${trackActivities.value.length} 条轨迹记录`)
        } else {
          ElMessage.info('该订单暂无轨迹记录')
        }
      } else {
        console.warn('轨迹数据格式异常:', trackData)
        ElMessage.warning('轨迹数据格式异常')
        trackActivities.value = []
      }
    } else {
      console.error('获取轨迹数据失败:', response.message)
      ElMessage.error('获取轨迹数据失败')
      trackActivities.value = []
    }
  } catch (error) {
    console.error('获取轨迹数据异常:', error)
    ElMessage.error('获取轨迹数据失败')
    trackActivities.value = []
  } finally {
    trackLoading.value = false
  }
}

// 添加一个状态来跟踪是否从URL参数中恢复选中的订单
const isRestoringFromUrl = ref(false)

// 从URL参数中获取选中的订单ID
const getSelectedOrderFromUrl = () => {
  const urlParams = new URLSearchParams(window.location.search)
  return urlParams.get('orderId')
}

// 保存选中的订单ID到URL参数
const saveSelectedOrderToUrl = (orderId: string | null) => {
  const url = new URL(window.location.href)
  if (orderId) {
    url.searchParams.set('orderId', orderId)
  } else {
    url.searchParams.delete('orderId')
  }
  window.history.replaceState({}, '', url.toString())
}

// 修改订单选择处理函数
const handleOrderChange = async (orderId: string) => {
  // 先清空当前数据避免渲染冲突
  trackActivities.value = []
  selectedOrder.value = orderId
  console.log('订单选择变化:', orderId)
  
  // 保存到URL参数
  saveSelectedOrderToUrl(orderId)
  
  // 获取轨迹数据
  if (orderId) {
    await fetchTrackData(orderId)
  }
}

const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
  console.log('搜索关键词:', searchKeyword.value)
}

const handleStatusFilter = () => {
  // 筛选逻辑已在计算属性中处理
  console.log('状态筛选:', statusFilter.value)
}

const refreshData = async () => {
  refreshing.value = true
  try {
    await fetchOrderList()
    if (selectedOrder.value) {
      await fetchTrackData(selectedOrder.value)
    }
    ElMessage.success('数据刷新成功')
  } catch (error) {
    ElMessage.error('数据刷新失败')
  } finally {
    refreshing.value = false
  }
}

const refreshTrackData = () => {
  if (selectedOrder.value) {
    fetchTrackData(selectedOrder.value)
  }
}

const selectFirstOrder = () => {
  if (filteredOrderOptions.value.length > 0) {
    handleOrderChange(filteredOrderOptions.value[0].value)
  }
}

// 地图控制方法
const zoomIn = () => {
  mapContainerRef.value?.zoomIn()
}

const zoomOut = () => {
  mapContainerRef.value?.zoomOut()
}

const resetMap = () => {
  mapContainerRef.value?.resetView()
}

const handleShowOnMap = (activity: any) => {
  console.log('在地图上显示位置:', activity)
  // 这里可以实现在地图上显示特定位置的逻辑
  if (activity.coordinates && mapContainerRef.value) {
    // 地图缩放到特定位置
    mapContainerRef.value.centerToCoordinates?.(activity.coordinates)
  } else {
    ElMessage.info('该轨迹点暂无坐标信息')
  }
}

// 监听器
watch(selectedOrder, (newOrderId) => {
  if (newOrderId) {
    // 可以在这里添加额外的逻辑
  }
})

onMounted(() => {
  // 只加载订单列表，不自动选择订单或加载轨迹数据
  fetchOrderList().then(() => {
    ElMessage.info('请选择订单查看物流轨迹')
  })
})
</script>

<style scoped>
.track-container {
  padding: 20px;
  min-height: calc(100vh - 120px);
}

.search-card {
  margin-bottom: 20px;
}

.search-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 20px;
  flex-wrap: wrap;
}

.search-inputs {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
  align-items: center;
}

.search-stats {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
  align-items: center;
}

.main-content {
  display: grid;
  grid-template-columns: 2fr 1fr;
  gap: 24px;
  height: calc(100vh - 240px);
  min-height: 600px;
}

.map-card, .track-info-card {
  display: flex;
  flex-direction: column;
  border-radius: 8px;
  transition: all 0.3s;
  height: 100%;
  overflow: hidden;
}

.map-card:hover, .track-info-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
  padding: 4px 0;
}

.header-info h3 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 18px;
  font-weight: 600;
}

.order-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.route-info {
  color: #606266;
  font-size: 14px;
}

.map-container {
  flex: 1;
  min-height: 400px;
}

.track-content {
  flex: 1;
  overflow-y: auto;
  min-height: 0;
  padding: 16px 0;
  max-height: calc(100vh - 400px);
}

/* 自定义滚动条样式 */
.track-content::-webkit-scrollbar {
  width: 8px;
}

.track-content::-webkit-scrollbar-track {
  background: #f1f5f9;
  border-radius: 4px;
}

.track-content::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 4px;
  transition: background 0.2s;
}

.track-content::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}

.track-stats {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
  margin-top: 12px;
}

.empty-state, .loading-state {
  padding: 60px 20px;
  text-align: center;
}

.track-actions {
  display: flex;
  gap: 8px;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .main-content {
    grid-template-columns: 1fr;
    height: auto;
  }
  
  .map-card, .track-info-card {
    height: 500px;
    max-height: 500px;
  }
  
  .track-content {
    max-height: calc(500px - 120px);
  }
}

/* 地图图例样式 */
.map-legend {
  margin-top: 16px;
  padding: 12px 16px;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  backdrop-filter: blur(10px);
}

.legend-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 12px;
}

.legend-items {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  color: #606266;
}

.legend-line {
  width: 24px;
  height: 3px;
  border-radius: 2px;
}

.legend-line.expected {
  background: #1890FF;
  border: 2px dashed #1890FF;
  height: 1px;
}

.legend-line.actual {
  background: #FF6B35;
}

.legend-marker {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 10px;
  font-weight: bold;
  color: white;
}

.legend-marker.start {
  background: #1890FF;
}

.legend-marker.start::after {
  content: '起';
}

.legend-marker.end {
  background: #52C41A;
}

.legend-marker.end::after {
  content: '终';
}

.legend-marker.current {
  background: transparent;
  color: #FF6B35;
  font-size: 14px;
}

.legend-note {
  margin-top: 12px;
  padding-top: 8px;
  border-top: 1px solid #f0f0f0;
  text-align: center;
}

.legend-note small {
  color: #8492a6;
  font-style: italic;
}

@media (max-width: 768px) {
  .track-container {
    padding: 16px;
  }
  
  .header-content {
    flex-direction: column;
    text-align: center;
    gap: 16px;
  }
  
  .search-section {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-inputs {
    flex-direction: column;
  }
  
  .search-inputs > * {
    width: 100%;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .map-card, .track-info-card {
    height: 400px;
    max-height: 400px;
  }
  
  .track-content {
    max-height: calc(400px - 120px);
  }
  
  .legend-items {
    flex-direction: column;
    gap: 8px;
  }
  
  .legend-item {
    justify-content: flex-start;
  }
}
</style>